﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Cashier_Model;
using Cashier_Service;
using Cashier.utils;
using Cashier_Interface;
using Cashier.prints;

namespace Cashier.finance
{
    public partial class DebtBillShipmentAddForm : Form
    {
        private MainForm mainform;
        private DataGridViewRow dgvRow;
        private IReloadData iReloadData;
        private BillShipmentRepaymentService repaymentService;
        private BillShipmentService shipmentService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mainform"></param>
        /// <param name="dgvRow"></param>
        /// <param name="debtAmount"></param>
        /// <param name="iReloadData"></param>
        public DebtBillShipmentAddForm(MainForm mainform, DataGridViewRow dgvRow, decimal debtAmount, IReloadData iReloadData)
        {
            InitializeComponent();
            this.mainform = mainform;
            this.dgvRow = dgvRow;
            this.iReloadData = iReloadData;
            this.repaymentService = new BillShipmentRepaymentService();
            this.shipmentService = new BillShipmentService();

            this.ControlsSetRights();
            this.InitialFormData();
            label_debtAmount.Text = debtAmount.ToString("f2");
            textbox_payAmount.LostFocus += new EventHandler(textbox_payAmount_LostFocus);
            textbox_giveAmount.LostFocus += new EventHandler(textbox_giveAmount_LostFocus);
        }

        /// <summary>
        /// 初始化Form数据
        /// </summary>
        private void InitialFormData()
        {
            if (this.dgvRow != null)
            {
                label_shipmentno.Text = dgvRow.Cells["shipment_no"].Value.ToString();
                label_memberno.Text = dgvRow.Cells["member_no"].Value.ToString();
                label_shipmentTotal.Text = ((decimal)dgvRow.Cells["shipment_total"].Value).ToString("f2");

                String memberName = String.Empty;
                Member member = new MemberService().GetMember(0, label_memberno.Text);
                if (member != null)
                    memberName = member.Name;
                label_memberName.Text = memberName;
            }
        }

        #region 功能方法实现

        /// <summary>
        /// 控件设置权限
        /// </summary>
        private void ControlsSetRights()
        {
            Button[] buttons = { button_save };
            RightsforControls.RightsforButton(mainform.Admin.RolePurviewtable, buttons);
        }

        /// <summary>
        /// 支付结果
        /// </summary>
        private void PayResult()
        {
            try
            {
                decimal shipmentTotal = Decimal.Parse(label_shipmentTotal.Text);
                decimal debtAmount = Decimal.Parse(label_debtAmount.Text);
                decimal payAmount = String.IsNullOrEmpty(textbox_payAmount.Text.Trim())?0:Decimal.Parse(textbox_payAmount.Text.Trim());
                decimal giveAmount = 0M;
                decimal remainAmount = 0M;

                if (payAmount > debtAmount)
                {
                    giveAmount = payAmount - debtAmount;
                    textbox_giveAmount.Text = giveAmount.ToString("f2");
                    label_remainAmount.Text = "0";
                }
                else if (payAmount < debtAmount)
                {
                    textbox_giveAmount.Text = "0";
                    remainAmount = debtAmount - payAmount;
                    label_remainAmount.Text = remainAmount.ToString("f2");
                }
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        /// <summary>
        /// 找零结果
        /// </summary>
        private void GiveResult()
        {
            try
            {
                decimal debtAmount = Decimal.Parse(label_debtAmount.Text);
                decimal payAmount = String.IsNullOrEmpty(textbox_payAmount.Text.Trim())?0:Decimal.Parse(textbox_payAmount.Text.Trim());
                decimal giveAmount = String.IsNullOrEmpty(textbox_giveAmount.Text.Trim())?0:Decimal.Parse(textbox_giveAmount.Text.Trim());
                decimal remainAmount = debtAmount - (payAmount - giveAmount);
                if (remainAmount > 0)
                    label_remainAmount.Text = remainAmount.ToString("f2");
                else
                    label_remainAmount.Text = "0";
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        /// <summary>
        /// 打印付款小票
        /// </summary>
        private void PrintPaymentList()
        {
            if (Config.TICKET_PRINT_PREVIEW)
            {
                PrintPreviewDialog previewDialog = new PrintPreviewDialog();
                previewDialog.Document = printDocument1;
                previewDialog.PrintPreviewControl.Zoom = 1;
                previewDialog.ShowDialog();
            }
            else
            {
                printDocument1.Print();
            }
        }

        #endregion

        #region 控件事件

        /// <summary>
        /// 还款金额
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textbox_payAmount_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((int)e.KeyChar == 13)
            {
                this.PayResult();
                textbox_giveAmount.Focus();
            }
        }

        /// <summary>
        /// 失去焦点事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textbox_payAmount_LostFocus(object sender, EventArgs e)
        {
            this.PayResult();
        }

        /// <summary>
        /// 找零金额
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textbox_giveAmount_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((int)e.KeyChar == 13)
            {
                this.GiveResult();
                button_save.Focus();
            }
        }

        /// <summary>
        /// 失去焦点事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textbox_giveAmount_LostFocus(object sender, EventArgs e)
        {
            this.GiveResult();
        }

        /// <summary>
        /// 保存事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_save_Click(object sender, EventArgs e)
        {
            try
            {
                this.GiveResult();
                decimal shipmentTotal = Decimal.Parse(label_shipmentTotal.Text);
                decimal debtAmount = Decimal.Parse(label_debtAmount.Text);
                decimal payAmount = String.IsNullOrEmpty(textbox_payAmount.Text.Trim())?0:Decimal.Parse(textbox_payAmount.Text.Trim());
                decimal giveAmount = String.IsNullOrEmpty(textbox_giveAmount.Text.Trim())?0:Decimal.Parse(textbox_giveAmount.Text.Trim());
                decimal remainAmount = Decimal.Parse(label_remainAmount.Text);

                if (debtAmount <= 0)
                {
                    MessageBox.Show("该帐单所欠金额已结清！");
                    return;
                }
                if (payAmount <= 0)
                {
                    MessageBox.Show("请输入支付金额！");
                    return;
                }
                if ((giveAmount - payAmount) >= 0)
                {
                    MessageBox.Show("找零金额不允许超出支付金额！");
                    return;
                }

                BillShipmentRepayment repayment = new BillShipmentRepayment();
                repayment.EnterpriseNo = mainform.Admin.EnterpriseNo;
                repayment.StoreNo = mainform.Admin.StoreNo;
                repayment.ShipmentNo = label_shipmentno.Text;
                repayment.MemberNo = label_memberno.Text;
                repayment.MemberName = label_memberName.Text;
                repayment.ShipmentTotal = shipmentTotal;
                repayment.DebtAmount = debtAmount;
                repayment.PayAmount = payAmount;
                repayment.GiveAmount = giveAmount;
                repayment.RemainAmount = remainAmount;
                repayment.RepaymentDate = DateTime.Now;
                repayment.AdminUsername = mainform.Admin.Username;
                repayment.AdminName = mainform.Admin.Name;
                repayment.Createtime = DateTime.Now;
                long id = new BillShipmentRepaymentService().InsertBillShipmentRepayment(repayment);
                if (id > 0)
                {
                    MessageBox.Show("还款成功！");
                    this.Close();                    
                    if (iReloadData != null)
                        iReloadData.ReloadDataGridViewData(null);
                    this.PrintPaymentList();
                }
                else
                {
                    MessageBox.Show("还款失败！");
                }
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        /// <summary>
        /// 退出事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #endregion

        #region 重写方法

        /// <summary>
        /// 键盘事件
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="keyData"></param>
        /// <returns></returns>
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            bool b = base.ProcessCmdKey(ref msg, keyData);
            switch (keyData)
            {
                case Keys.Escape:
                    this.Close();
                    break;
            }
            return b;
        }

        #endregion

        #region 打印事件

        /// <summary>
        /// 打印付款小票
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            try
            {
                String shipmentno = label_shipmentno.Text;
                using (e.Graphics)
                {
                    int rectWidth = 185; //矩形宽
                    int lineHeight = 14; //矩形高
                    //定义顶点的坐标
                    int x = 0, y = 0;

                    //定义矩形画笔
                    Pen rectPen = new Pen(Brushes.White, 1);
                    rectPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid;

                    //定义打印字体
                    Font font = new Font(new FontFamily("宋体"), 8);
                    StringFormatStyle sfs = new StringFormatStyle();

                    //定义分隔线
                    Pen splitLinePen = new Pen(Brushes.Black);
                    splitLinePen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;


                    //画矩形
                    Rectangle rect = new Rectangle(x, y, rectWidth, lineHeight);
                    //e.Graphics.FillRectangle(Brushes.White, rect);
                    e.Graphics.DrawRectangle(rectPen, rect);
                    String s = "=====付款小票=====";
                    e.Graphics.DrawString(s, font, Brushes.Black, rect, sfs.CenterMiddle);

                    //打印分隔线
                    e.Graphics.DrawLine(splitLinePen, x, rect.Y + rect.Height + 2, x + rect.Width, rect.Y + rect.Height + 2);

                    //打印票头信息
                    rect = new Rectangle(x, rect.Y + lineHeight + 6, rectWidth, lineHeight);
                    e.Graphics.DrawRectangle(rectPen, rect);
                    s = "打印时间：" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    e.Graphics.DrawString(s, font, Brushes.Black, rect, sfs.LeftMiddle);

                    rect = new Rectangle(x, rect.Y + lineHeight, rectWidth, lineHeight);
                    e.Graphics.DrawRectangle(rectPen, rect);
                    s = "收款人：" + this.mainform.Admin.Name;
                    e.Graphics.DrawString(s, font, Brushes.Black, rect, sfs.LeftMiddle);

                    //打印分隔线
                    e.Graphics.DrawLine(splitLinePen, x, rect.Y + rect.Height + 2, x + rect.Width, rect.Y + rect.Height + 2);

                    BillShipment shipment = shipmentService.GetBillShipment(0, shipmentno);
                    if (shipment != null)
                    {
                        rect = new Rectangle(x, rect.Y + lineHeight + 6, 110, lineHeight);
                        e.Graphics.DrawRectangle(rectPen, rect);
                        s = "商品数量：";
                        e.Graphics.DrawString(s, font, Brushes.Black, rect, sfs.LeftMiddle);

                        rect = new Rectangle(x + rect.Width, rect.Y, rectWidth - rect.Width, lineHeight);
                        e.Graphics.DrawRectangle(rectPen, rect);
                        s = shipment.Numbers.ToString();
                        e.Graphics.DrawString(s, font, Brushes.Black, rect, sfs.RightMiddle);

                        rect = new Rectangle(x, rect.Y + lineHeight, 110, lineHeight);
                        e.Graphics.DrawRectangle(rectPen, rect);
                        s = "总金额：";
                        e.Graphics.DrawString(s, font, Brushes.Black, rect, sfs.LeftMiddle);

                        rect = new Rectangle(x + rect.Width, rect.Y, rectWidth - rect.Width, lineHeight);
                        e.Graphics.DrawRectangle(rectPen, rect);
                        s = shipment.ShipmentTotal.ToString("f2");
                        e.Graphics.DrawString(s, font, Brushes.Black, rect, sfs.RightMiddle);

                        rect = new Rectangle(x, rect.Y + lineHeight, 110, lineHeight);
                        e.Graphics.DrawRectangle(rectPen, rect);
                        s = "已付款：";
                        e.Graphics.DrawString(s, font, Brushes.Black, rect, sfs.LeftMiddle);

                        rect = new Rectangle(x + rect.Width, rect.Y, rectWidth - rect.Width, lineHeight);
                        e.Graphics.DrawRectangle(rectPen, rect);
                        s = shipment.PayAmount.ToString("f2");
                        e.Graphics.DrawString(s, font, Brushes.Black, rect, sfs.RightMiddle);

                        rect = new Rectangle(x, rect.Y + lineHeight, 110, lineHeight);
                        e.Graphics.DrawRectangle(rectPen, rect);
                        s = "欠款：";
                        e.Graphics.DrawString(s, font, Brushes.Black, rect, sfs.LeftMiddle);

                        rect = new Rectangle(x + rect.Width, rect.Y, rectWidth - rect.Width, lineHeight);
                        e.Graphics.DrawRectangle(rectPen, rect);
                        s = shipment.DebtAmount.ToString("f2");
                        e.Graphics.DrawString(s, font, Brushes.Black, rect, sfs.RightMiddle);

                        //打印分隔线
                        e.Graphics.DrawLine(splitLinePen, x, rect.Y + rect.Height + 2, rectWidth, rect.Y + rect.Height + 2);

                        DataTable dt = repaymentService.GetBillShipmentRepaymentTable(0, 0, mainform.Admin.EnterpriseNo, shipmentno, 
                            null, mainform.UsernameForQuery, "id", null);
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            int tempX = x, tempY = rect.Y + lineHeight + 6;
                            String repaymentDate = String.Empty, repaymentUser = String.Empty;
                            decimal payAmount = 0M, remainAmount = 0M, giveAmount = 0M;
                            int rectLeftWidht = 80;
                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                DataRow row = dt.Rows[i];
                                repaymentDate = ((DateTime)row["repayment_date"]).ToString("yyyy-MM-dd HH:mm");
                                repaymentUser = row["repayment_user"].ToString();
                                payAmount = (decimal)row["pay_amount"];
                                remainAmount = (decimal)row["remain_amount"];
                                giveAmount = (decimal)row["give_amount"];

                                rect = new Rectangle(tempX, tempY, rectLeftWidht, lineHeight);
                                e.Graphics.DrawRectangle(rectPen, rect);
                                s = "付款日期：";
                                e.Graphics.DrawString(s, font, Brushes.Black, rect, sfs.LeftMiddle);

                                rect = new Rectangle(tempX + rect.Width, rect.Y, rectWidth - rect.Width, lineHeight);
                                e.Graphics.DrawRectangle(rectPen, rect);
                                s = repaymentDate;
                                e.Graphics.DrawString(s, font, Brushes.Black, rect, sfs.RightMiddle);

                                rect = new Rectangle(tempX, rect.Y + lineHeight, rectLeftWidht, lineHeight);
                                e.Graphics.DrawRectangle(rectPen, rect);
                                s = "付款金额：";
                                e.Graphics.DrawString(s, font, Brushes.Black, rect, sfs.LeftMiddle);

                                rect = new Rectangle(tempX + rect.Width, rect.Y, rectWidth - rect.Width, lineHeight);
                                e.Graphics.DrawRectangle(rectPen, rect);
                                s = payAmount.ToString("f2");
                                e.Graphics.DrawString(s, font, Brushes.Black, rect, sfs.RightMiddle);

                                rect = new Rectangle(tempX, rect.Y + lineHeight, rectLeftWidht, lineHeight);
                                e.Graphics.DrawRectangle(rectPen, rect);
                                s = "欠款金额：";
                                e.Graphics.DrawString(s, font, Brushes.Black, rect, sfs.LeftMiddle);

                                rect = new Rectangle(tempX + rect.Width, rect.Y, rectWidth - rect.Width, lineHeight);
                                e.Graphics.DrawRectangle(rectPen, rect);
                                s = remainAmount.ToString("f2");
                                e.Graphics.DrawString(s, font, Brushes.Black, rect, sfs.RightMiddle);

                                if (giveAmount > 0)
                                {
                                    rect = new Rectangle(tempX, rect.Y + lineHeight, rectLeftWidht, lineHeight);
                                    e.Graphics.DrawRectangle(rectPen, rect);
                                    s = "找零金额：";
                                    e.Graphics.DrawString(s, font, Brushes.Black, rect, sfs.LeftMiddle);

                                    rect = new Rectangle(tempX + rect.Width, rect.Y, rectWidth - rect.Width, lineHeight);
                                    e.Graphics.DrawRectangle(rectPen, rect);
                                    s = giveAmount.ToString("f2");
                                    e.Graphics.DrawString(s, font, Brushes.Black, rect, sfs.RightMiddle);
                                }

                                if (i < (dt.Rows.Count - 1))
                                {
                                    //打印分隔线
                                    e.Graphics.DrawLine(splitLinePen, tempX, rect.Y + rect.Height + 2, x + rectWidth, rect.Y + rect.Height + 2);

                                    tempX = x;
                                    tempY = rect.Y + lineHeight + 4;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        #endregion
    }
}
